<?

/*
Autor: Imanol Iglesias
email: imanolif@gmail.com
*/

define('IMAP_MAILBOX', '{imap.gmail.com:993/imap/ssl}');
define('IMAP_USER', 'usuario');
define('IMAP_PASSWORD', 'password');

include('Email.php');

class Imap
{
	private $mailbox;
	private $user;
	private $password;
	private $inbox = null;
	private $info = null;
	private $emails = array();
	
	public function __construct($mailbox, $user, $password)
	{
		$this->mailbox = $mailbox;
		$this->user = $user;
		$this->password = $password;
	}
		
	public function open()
	{
		$this->inbox = imap_open($this->mailbox, $this->user, $this->password);
		$this->info = imap_check($this->inbox);
		$this->emails = imap_fetch_overview($this->inbox, "1:{$this->info->Nmsgs}", 0);
	}
	
	public function getEmailsNuevos($marcarComoLeidos = true)
	{
		if ($this->inbox == null)
			return;
			
		$emailsNuevos = array();
		
		foreach ($this->emails as $email) 
		{
			if (!$email->seen)
			{
				$emailsNuevos[] = new Email($email->from, 
											  $email->date, 
											  $email->subject, 
											  imap_fetchbody($this->inbox, $email->msgno, 1));
				
				if ($marcarComoLeidos)
	        		imap_setflag_full($this->inbox, $email->uid, '\\SEEN', SE_UID); 
	        }
		}
		
		return $emailsNuevos;
	}
	
	function __destruct()
	{
		imap_close($this->inbox);
	}
}

/*
echo '<pre>';
$imap = new Imap(IMAP_MAILBOX, IMAP_USER, IMAP_PASSWORD);
$imap->open();
var_dump($imap->getEmailsNuevos(false));
echo '</pre>';
*/

?>